package kitwee.com.kanpad.orderDetail;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import kitwee.com.kanpad.BaseFragment;
import kitwee.com.kanpad.BuildConfig;
import kitwee.com.kanpad.R;
import kitwee.com.kanpad.bean.DepartmentInfo;
import kitwee.com.kanpad.bean.DepartmentListAdapter;
import kitwee.com.kanpad.bean.ListDetailBean;
import kitwee.com.kanpad.bean.TaskListBean;
import okhttp3.Call;
import utils.FlavorHelper;
import utils.SPUtils;

/**
 * @author GanQuan
 * @date 2018/1/22
 */

public class ChangeWorkFragment extends BaseFragment {


    @BindView(R.id.work_people)
    RecyclerView workPeople;
    @BindView(R.id.cancel)
    TextView cancel;
    @BindView(R.id.tv_sure)
    TextView tvSure;
    @BindView(R.id.bottom)
    LinearLayout bottom;
    @BindView(R.id.report)
    TextView report;
    @BindView(R.id.rl_department)
    RelativeLayout rlDepartment;
    @BindView(R.id.sub_number)
    EditText subNumber;
    @BindView(R.id.sub_good_number)
    EditText subGoodNumber;
    @BindView(R.id.sub_bad_number)
    EditText subBadNumber;
    @BindView(R.id.sub_time)
    EditText subTime;
    @BindView(R.id.sub_sure)
    TextView subSure;
    @BindView(R.id.sub_cancel)
    TextView subCancel;
    @BindView(R.id.rl_submit)
    RelativeLayout rlSubmit;
    private View layout;
    private DepartmentListAdapter departmentListAdapter;
    private String endpoint;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        layout = inflater.inflate(R.layout.department_list, container, false);
        ButterKnife.bind(this, layout);
        return layout;
    }


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        endpoint = BuildConfig.API_ENDPOINT;
        initView();
//        initDepartment();
    }


    private List<DepartmentInfo.DataBean.RowsBean> departmentList;

    private String departmentID;
    private String departName;

    private void initView() {
        departmentList = new ArrayList<>();
        workPeople.setLayoutManager(new GridLayoutManager(getActivity(), 3));
        departmentListAdapter = new DepartmentListAdapter(departmentList, getActivity());
        workPeople.setAdapter(departmentListAdapter);
        departmentListAdapter.setOnItemClickLitener(new DepartmentListAdapter.OnItemClickLitener() {
            @Override
            public void onItemClick(View view, int position) {
                departmentID = departmentList.get(position).getId();
                departName = departmentList.get(position).getName();
            }
        });

        if (FlavorHelper.isXiongTian()) {
            report.setVisibility(View.GONE);
        }
    }

    public static TaskListBean.RowsBean rowsBean;

    public static ChangeWorkFragment newInstance(TaskListBean.RowsBean beans) {
        rowsBean = beans;
        return new ChangeWorkFragment();
    }


    @Override
    public void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onShowMessageEvent(OrderDetailEvent orderDetailEvent) {
        LogUtils.e("消息 : " + orderDetailEvent.getListDetailBean().getKanbanMessageVOList());
        List<ListDetailBean.KanbanMessageVOListBean> kanbanMessageVOList = orderDetailEvent.getListDetailBean().getKanbanMessageVOList();


    }

    @Override
    public void onResume() {
        super.onResume();

    }

    private void initDepartment() {

        String user = SPUtils.getString(getActivity(), "user");
        String key = SPUtils.getString(getActivity(), "key");
        final long time = System.currentTimeMillis();
        final String digest = new String(Hex.encodeHex(DigestUtils.md5((key + user + time).getBytes())));
        String timer = String.valueOf(time);

        OkHttpUtils.get()
                .tag(this)
//                .url(KanpadStrings.HOSTURL + "/deviceStatusRecords/findUserList")
                .url(endpoint + "/deviceStatusRecords/findUserList")
                .addParams("pun", user)
                .addParams("pd", digest)
                .addParams("t", timer)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                    }

                    @Override
                    public void onResponse(String response, int id) {

                        JSONObject jsonObj = JSON.parseObject(response);
                        JSONObject data = jsonObj.getJSONObject("data");
                        JSONArray rows = data.getJSONArray("rows");
                        List<DepartmentInfo.DataBean.RowsBean> departList = JSON.parseArray(rows.toString(), DepartmentInfo.DataBean.RowsBean.class);

                        for (int i = 0; i < departList.size(); i++) {
                            if (departList.get(i).getRole_name() != null && TextUtils.equals("开机员", departList.get(i).getRole_name())) {
                                departmentList.add(departList.get(i));
                                LogUtils.e(departList.get(i).getName());
                            }
                        }
                        LogUtils.e("departmentList  : " + departmentList.size());
                        departmentListAdapter.notifyDataSetChanged();
                    }
                });
    }


    private void succession(String id) {
        String user = SPUtils.getString(getActivity(), "user");
        String key = SPUtils.getString(getActivity(), "key");
        final long time = System.currentTimeMillis();
        final String digest = new String(Hex.encodeHex(DigestUtils.md5((key + user + time).getBytes())));
        String timer = String.valueOf(time);
        OkHttpUtils.get()
                .tag(this)
                .url(endpoint + "/deviceStatusRecords/stopTask")
//                .url(KanpadStrings.HOSTURL + "/deviceStatusRecords/stopTask")
                .addParams("pun", user)
                .addParams("pd", digest)
                .addParams("t", timer)
                .addParams("leader_name", id)
                .addParams("task_id", rowsBean.getId())
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        LogUtils.e("换班失败 ; " + e.getMessage());
                        ToastUtils.showShort("换班失败,请重试");
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        JSONObject jsonObj = JSON.parseObject(response);
                        String data = jsonObj.getString("statusCode");
                        if (TextUtils.equals("200", data)) {
                            getActivity().finish();
                            LogUtils.e("换班成功 ; " + response);
                        } else {
                            LogUtils.e("换班失败 ; " + jsonObj.getString("message"));
                            ToastUtils.showShort("换班失败,请重试");
                        }
                    }
                });

    }


    @OnClick({R.id.cancel, R.id.tv_sure, R.id.report, R.id.sub_sure, R.id.sub_cancel})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.cancel:
                EventBus.getDefault().postSticky(new ChangeWorkEvent("cancel"));
                break;
            case R.id.tv_sure:
                if (FlavorHelper.isXiongTian()) {
                    succession(departmentID);
                } else {
                    if (ISCANCHANGWORK) {
                        succession(departmentID);
                    } else {
                        ToastUtils.showShort("请先报工");
                    }
                }


                break;
            case R.id.report:
                rlSubmit.setVisibility(View.VISIBLE);
                rlDepartment.setVisibility(View.GONE);
                break;
            case R.id.sub_sure:
                String s = subNumber.getText().toString();
                String s1 = subBadNumber.getText().toString();
                String s2 = subGoodNumber.getText().toString();
                String s3 = subTime.getText().toString();

                if (TextUtils.equals("", s) && TextUtils.equals("", s1) && TextUtils.equals("", s2) && TextUtils.equals("", s3)) {
                    ToastUtils.showShort("报工参数不能为空");
                } else {
                    reportWork();
                }
                break;
            case R.id.sub_cancel:
                rlSubmit.setVisibility(View.GONE);
                rlDepartment.setVisibility(View.VISIBLE);
                break;
        }
    }

    private boolean ISCANCHANGWORK = false;

    /**
     * 报工
     */
    private void reportWork() {
        if (subNumber.getText().toString() != null) {
            String number = subNumber.getText().toString();
            String goodNumber = subGoodNumber.getText().toString();
            String badNumber = subBadNumber.getText().toString();
            String continuedTime = subTime.getText().toString();

            String user = SPUtils.getString(getActivity(), "user");
            String key = SPUtils.getString(getActivity(), "key");
            final long time = System.currentTimeMillis();
            final String digest = new String(Hex.encodeHex(DigestUtils.md5((key + user + time).getBytes())));
            String timer = String.valueOf(time);
            OkHttpUtils.get()
                    .tag(this)
//                    .url(KanpadStrings.HOSTURL + "/deviceStatusRecords/addproduction")
                    .url(endpoint + "/deviceStatusRecords/addproduction")
                    .addParams("pun", user)
                    .addParams("pd", digest)
                    .addParams("t", timer)
                    .addParams("confirmed_production", number)
                    .addParams("badProductAmount", badNumber)
                    .addParams("goodProductAmount", goodNumber)
                    .addParams("run_time", continuedTime)
                    .addParams("taskId", rowsBean.getId())
                    .build()
                    .execute(new StringCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {
                            LogUtils.e("报工失败 ; " + e.getMessage());

                            ISCANCHANGWORK = false;
                        }

                        @Override
                        public void onResponse(String response, int id) {

                            JSONObject jsonObj = JSON.parseObject(response);
                            String data = jsonObj.getString("statusCode");
                            if (TextUtils.equals("200", data)) {
                                ToastUtils.showShort("报工成功");
                                rlSubmit.setVisibility(View.GONE);
                                rlDepartment.setVisibility(View.VISIBLE);
                                ISCANCHANGWORK = true;

                            }

                        }
                    });
        }
    }
}
